package com.tempjob.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

/**
 * @author jiuhui
 * @version HttpRequest.java, v 0.1
 * @date 2017年12月11日 下午1:42:24
 * 默认超时时间3000毫秒
 */
public class HttpUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url   发送请求的URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param, Map<String, String> property) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url;
            if (!StringUtils.isEmpty(param)) {
                urlNameString = url + "?" + param;
            }
//            LOGGER.info("GET url:" + urlNameString);
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            connection.setConnectTimeout(30000);
            connection.setReadTimeout(30000);
            // 设置通用的请求属性
//            connection.setRequestProperty("Cookie", cookie);
//            connection.setRequestProperty("accept", "application/json");
//            connection.setRequestProperty("Content-Type", "application/json");
//            connection.setRequestProperty("connection", "Keep-Alive");
//            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 设置通用的请求属性
            if (property != null && !property.isEmpty()) {
                Iterator<Entry<String, String>> iter = property.entrySet().iterator();
                while (iter.hasNext()) {
                    Entry<String, String> entry = (Entry<String, String>) iter.next();
                    connection.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
//            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
//			for (String key : map.keySet()) {
////				System.out.println(key + "--->" + map.get(key));
////			}
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            LOGGER.error("发送GET请求出现异常！", e);
//            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param, String cookie, Map<String, String> property) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            if (!StringUtils.isEmpty(cookie)) {
                conn.setRequestProperty("Cookie", "JSESSIONID=" + cookie);
            }
            conn.setRequestProperty("accept", "application/json");
//            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 设置通用的请求属性
            if (property != null && !property.isEmpty()) {
                Iterator<Entry<String, String>> iter = property.entrySet().iterator();
                while (iter.hasNext()) {
                    Entry<String, String> entry = (Entry<String, String>) iter.next();
                    conn.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }
            conn.setConnectTimeout(60000);
            conn.setReadTimeout(60000);
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            LOGGER.error("发送 POST 请求出现异常！", e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }


    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param uri   发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendBodyPost(String uri, String param, String cookie) {
        BufferedReader reader = null;
        HttpURLConnection con = null;
        StringBuffer sbf = new StringBuffer();

        try {
            URL url = new URL(uri);
            // 打开和URL之间的连接
            con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("POST");//请求post方式
            con.setUseCaches(false); // Post请求不能使用缓存
            con.setDoInput(true);// 设置是否从HttpURLConnection输入，默认值为 true
            con.setDoOutput(true);// 设置是否使用HttpURLConnection进行输出，默认值为 false
            if (!StringUtils.isEmpty(cookie)) {
                con.setRequestProperty("Cookie", "JSESSIONID=" + cookie);
            }
//            con.setRequestProperty("accept", "application/json");
            con.setRequestProperty("accept", "*/*");
            con.setRequestProperty("Charset", "UTF-8");
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
//            con.setRequestProperty("Content-Type", "application/json");
            con.setRequestProperty("connection", "Keep-Alive");
            con.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            con.setConnectTimeout(10000);
            con.setReadTimeout(30000);

            // 建立实际的连接
            con.connect();
            String strRead = null;

            // 得到请求的输出流对象
            OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
            writer.write(param);
            writer.flush();
            // 获取服务端响应，通过输入流来读取URL的响应
            InputStream is;
            try {
                is = con.getInputStream();
            }catch (SocketTimeoutException te){
                Thread.sleep(10000);
                is = con.getInputStream();
            }
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
        }
//        catch (ProtocolException e) {
//            throw new RuntimeException(e);
//        } catch (MalformedURLException e) {
//            throw new RuntimeException(e);
//        } catch (UnsupportedEncodingException e) {
//            throw new RuntimeException(e);
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
        catch (Exception e) {
            LOGGER.error("发送 POST 请求出现异常！", e);
        }
        finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 关闭连接
            if (con != null) {
                con.disconnect();
            }
        }
        // 打印读到的响应结果
//        System.out.println("运行结束："+sbf.toString());
        return sbf.toString();
    }

    public static String sendBodyPostJson(String uri, String param, String cookie) {
        BufferedReader reader = null;
        HttpURLConnection con = null;
        StringBuffer sbf = new StringBuffer();

        try {
            URL url = new URL(uri);
            // 打开和URL之间的连接
            con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("POST");//请求post方式
            con.setUseCaches(false); // Post请求不能使用缓存
            con.setDoInput(true);// 设置是否从HttpURLConnection输入，默认值为 true
            con.setDoOutput(true);// 设置是否使用HttpURLConnection进行输出，默认值为 false
            if (!StringUtils.isEmpty(cookie)) {
                con.setRequestProperty("Cookie", "JSESSIONID=" + cookie);
            }
//            con.setRequestProperty("accept", "application/json");
            con.setRequestProperty("accept", "*/*");
            con.setRequestProperty("Charset", "UTF-8");
//            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            con.setRequestProperty("Content-Type", "application/json");
            con.setRequestProperty("connection", "Keep-Alive");
            con.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            con.setConnectTimeout(10000);
            con.setReadTimeout(30000);

            // 建立实际的连接
            con.connect();
            String strRead = null;

            // 得到请求的输出流对象
            OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
            writer.write(param);
            writer.flush();
            // 获取服务端响应，通过输入流来读取URL的响应
            InputStream is;
            try {
                is = con.getInputStream();
            }catch (SocketTimeoutException te){
                Thread.sleep(10000);
                is = con.getInputStream();
            }
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
        }
//        catch (ProtocolException e) {
//            throw new RuntimeException(e);
//        } catch (MalformedURLException e) {
//            throw new RuntimeException(e);
//        } catch (UnsupportedEncodingException e) {
//            throw new RuntimeException(e);
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
        catch (Exception e) {
            LOGGER.error("发送 POST 请求出现异常！", e);
        }
        finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 关闭连接
            if (con != null) {
                con.disconnect();
            }
        }
        // 打印读到的响应结果
//        System.out.println("运行结束："+sbf.toString());
        return sbf.toString();
    }

}
